package udpserver

import (
	"fmt"
	"strings"
)


//十进制切片数组转换为16进制字符串
func Tool_DecimalByteSlice2HexString(DecimalSlice []byte) string {
	var sa = make([]string, 0)
	for _, v := range DecimalSlice {
		sa = append(sa, fmt.Sprintf("%02X", v))
	}
	ss := strings.Join(sa, "")
	return ss
}


//hexadecimal to Decimal
func HexDecc(h string) (n int64) {
	s := strings.Split(strings.ToUpper(h), "")
	l := len(s)
	i := 0
	d := float64(0)
	hex := map[string]string{"A": "10", "B": "11", "C": "12", "D": "13", "E": "14", "F": "15"}
	for i = 0; i < l; i++ {
		c := s[i]
		if v, ok := hex[c]; ok {
			c = v
		}
		f, err := strconv.ParseFloat(c, 10)
		if err != nil {
			log.Println("Hexadecimal to decimal error:", err.Error())
			return -1
		}
		d += f * math.Pow(16, float64(l-i-1))
	}
	return int64(d)
}


//根据ascii码表将 []byte 转换为 string
func BytesToString(b []byte) string {
	bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	sh := reflect.StringHeader{bh.Data, bh.Len}
	return *(*string)(unsafe.Pointer(&sh))
}


//十六进制字符逐个字节异或
func Xor(ss string) string {
	tmp := " "
	//先由十六进制字符串转成十进制字符串，然后转成十进制整形，最后异或
	for i := 4; i < len(ss); i++ {
		//fmt.Println("start")
		if i == 4 {
			tmp = "00"
		}
		sss := ss[i : i+2]

		//fmt.Println("sss:",sss)
		dss1, _ := strconv.Atoi(tmp)
		dss2, _ := strconv.Atoi(strconv.FormatInt(HexDecc(sss), 10))
		//fmt.Println("dss2:",dss2)
		//转成十进制进行异或
		tmp = strconv.Itoa(dss1 ^ dss2)
		//fmt.Println("============1=============")
		//fmt.Println(dss1)
		//fmt.Println(dss2)
		//fmt.Println("tmp:", tmp)
		//fmt.Println("============2==============")
		i++
	}
	tmp1,_ := strconv.ParseInt(tmp, 10, 64)
	return 	 DecHex(tmp1)
}


// Decimal to hexadecimal
func DecHex(n int64) string {
	if n < 0 {
		log.Println("Decimal to hexadecimal error: the argument must be greater than zero.")
		return ""
	}
	if n == 0 {
		return "0"
	}
	hex := map[int64]int64{10: 65, 11: 66, 12: 67, 13: 68, 14: 69, 15: 70}
	s := ""
	for q := n; q > 0; q = q / 16 {
		m := q % 16
		if m > 9 && m < 16 {
			m = hex[m]
			s = fmt.Sprintf("%v%v", string(m), s)
			continue
		}
		s = fmt.Sprintf("%v%v", m, s)
	}
	return s
}




